package io.kiki.stack.http.feign.form.multipart;

import feign.codec.EncodeException;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.val;

import static io.kiki.stack.http.feign.form.util.PojoUtil.isUserPojo;
import static io.kiki.stack.http.feign.form.util.PojoUtil.toMap;
import static lombok.AccessLevel.PRIVATE;

/**
 * A custom user's POJO writer.
 *
 * @author Artem Labazin
 */
@RequiredArgsConstructor
@FieldDefaults(level = PRIVATE, makeFinal = true)
public class PojoWriter extends AbstractWriter {

    Iterable<Writer> writers;

    @Override
    public boolean isApplicable(Object object) {
        return isUserPojo(object);
    }

    @Override
    public void write(Output output, String boundary, String key, Object object) throws EncodeException {
        val map = toMap(object);
        for (val entry : map.entrySet()) {
            val writer = findApplicableWriter(entry.getValue());
            if (writer == null) {
                continue;
            }

            writer.write(output, boundary, entry.getKey(), entry.getValue());
        }
    }

    private Writer findApplicableWriter(Object value) {
        for (val writer : writers) {
            if (writer.isApplicable(value)) {
                return writer;
            }
        }
        return null;
    }
}
